"""
数据库初始化工具
用于创建必要的数据库表和初始化数据
"""
from app import db
from app.models import Employee, Organization

def init_db():
    """初始化数据库"""
    # 创建所有表
    db.create_all()
    
    # 检查是否已存在组织数据
    org = Organization.query.first()
    if not org:
        # 创建示例组织数据
        org = Organization(
            name="倍智集团",
            total_employees=30,
            formal_employees=27,
            gender_ratio="1:1.14",
            avg_age=42.6,
            avg_tenure="2年5月",
            management_positions=9,
            reporting_depth=2.00,
            management_span=3.63,
            probation_count=6,
            party_member_ratio=33.33,
            campus_recruit_ratio=46.67,
            new_employee_ratio=0.00,
            turnover_rate=0.00,
            officer_soldier_ratio="1:1.56"
        )
        db.session.add(org)
    
    # 检查是否已存在员工数据
    if Employee.query.count() == 0:
        # 创建示例员工数据
        employees = [
            Employee(
                name="吴盛厚",
                department="倍智集团",
                position="副总经理",
                title="副总经理",
                level="M3",
                tags="久"
            ),
            Employee(
                name="陈兰枫",
                department="倍智集团",
                position="总经理",
                title="总经理",
                level="M4",
                tags="久"
            ),
            Employee(
                name="吴悦珠",
                department="广州总部",
                position="分部副总经理",
                title="分部副总经理",
                level="M3",
                tags="久"
            ),
            Employee(
                name="喻寒妍",
                department="广州总部",
                position="分部总经理",
                title="分部总经理",
                level="M3",
                tags="久"
            ),
            Employee(
                name="周婕梅",
                department="信息技术部",
                position="架构师",
                title="架构师",
                level="P1",
                tags="久,留"
            )
        ]
        for emp in employees:
            db.session.add(emp)
    
    # 提交所有更改
    try:
        db.session.commit()
        print("数据库初始化成功")
    except Exception as e:
        db.session.rollback()
        print(f"数据库初始化失败: {str(e)}")
        raise

if __name__ == "__main__":
    from app import app
    with app.app_context():
        init_db()
